package com.dream.base.web.interceptor;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dream.model.app.AppAbstractUser;
import com.dream.utils.annotation.AccessLog;
import com.dream.utils.web.provider.AccessLogProvider;
import com.dream.vo.base.Constants;
import com.google.common.collect.Maps;

/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2012/09/30
 */
public class AccessLogInterceptor extends HandlerInterceptorAdapter {

	private AccessLogProvider accessLogProvider;
	
	private Date startTime;
	
	public void setAccessLogProvider(AccessLogProvider accessLogProvider) {
		this.accessLogProvider = accessLogProvider;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws ServletException {
		startTime = new Date();
		return true;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)
	throws Exception {
		
		if (handler instanceof HandlerMethod) {

			Method method = (Method) ((HandlerMethod) handler).getMethod();

			if (method.isAnnotationPresent(AccessLog.class)) {

				AccessLog accessLog = method.getAnnotation(AccessLog.class);
				Map<String,String> requestInfo = Maps.newHashMap();
				requestInfo.put("ip=", request.getRemoteAddr());
				requestInfo.put("path=", request.getRequestURL().toString());
				requestInfo.put("class=", method.getDeclaringClass().getName());
				requestInfo.put("method=", method.getName());
				HttpSession session = request.getSession(false);
				if(session != null ){
					AppAbstractUser user = (AppAbstractUser)session.getAttribute(Constants.USER_ID);
					requestInfo.put("userId=", user==null?null:user.getId());
					requestInfo.put("userName=", user==null?null:user.getName());
				}
				Map<String,Date> accessMap = Maps.newHashMap();
				accessMap.put("start_time=",startTime);
				accessMap.put("end_time=", new Date());
				accessLogProvider.accesslog(accessLog,requestInfo,accessMap);
			}

		}
		super.afterCompletion(request, response, handler, ex);
	}
	
}
